package br.com.alugargaragem.ui.action;

import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.integration.spring.SpringBean;
import net.sourceforge.stripes.validation.EmailTypeConverter;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.ValidateNestedProperties;
import br.com.alugargaragem.domain.login.model.Login;
import br.com.alugargaragem.domain.login.service.LoginService;
import br.com.alugargaragem.ui.model.LoginData;
import br.com.alugargaragem.ui.stripes.action.AlugaGaragemActionBean;

public class LoginAction extends AlugaGaragemActionBean {

	@ValidateNestedProperties( {
			@Validate(field = "email", required = true, minlength = 3, maxlength = 255, trim = true, on = {
					"signin", "signup"
			}, converter = EmailTypeConverter.class),
			@Validate(field = "password", required = true, minlength = 6, maxlength = 12, on = {
					"signup", "signup"
			})
	})
	private Login login;

	@SpringBean
	private LoginService loginService;

	public Login getLogin() {
		return this.login;
	}

	public void setLogin(Login login) {
		this.login = login;
	}

	public Resolution signin() {
		Login login = this.loginService.signin(this.login);
		this.setLoginData(LoginData.create().login(login).build());
		return this.homeActionForward();
	}

	public Resolution signup() {
		this.loginService.signup(this.login);
		return this.homeActionForward();
	}

	@Override
	public Resolution view() {
		this.clearLogin();
		return this.forward();
	}

	private void clearLogin() {
		this.setLogin(null);
	}

	private Resolution homeActionForward() {
		return this.forward(HomeAction.class);
	}
}
